package com.cyandpos.pad.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;

import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.cyandpos.pad.R;
import com.cyandpos.pad.common.commondata.Constant;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.O2OPayDetail;
import com.cyandpos.pad.posdata.Order;
import com.cyandpos.pad.posdata.PayInfo;
import com.cyandpos.pad.posdata.Payment;
import com.cyandpos.pad.posdata.QueryOrderReq;
import com.cyandpos.pad.posdata.RefundOrder;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.posdata.YhkCardItem;
import com.cyandpos.pad.tradedetails.adapter.TradeDetailsiinfoAdapter;
import com.cyandpos.pad.tradedetails.presenter.TradeDetailsPresenter;
import com.cyandpos.pad.tradedetails.presenter.TradeDetailsPresenterImpl;
import com.cyandpos.pad.tradedetails.view.TimeThread;
import com.cyandpos.pad.tradedetails.view.TradeDetailsView;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.ToastUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

public class DetailsActivity extends BaseActivity implements TradeDetailsView, View.OnClickListener {

    private TradeDetailsPresenter mTradeDetailsPresenter;
    private ProgressDialog dialog;
    private TradeDetailsiinfoAdapter tradeDetailsiinfoAdapter;
    private QueryOrderReq orderReq;
    private String sktno,orderNo,jlbh,endtime,begintime;
    private Order tradeDetail;
    @BindView(R.id.btn_details_exit_system)
    Button btndetailsexitsystem;
    @BindView(R.id.details_edittext_order)
    TextView detailsedittextorder;
    @BindView(R.id.details_edittext_endtime)
    TextView detailsedittext_endtime;
    @BindView(R.id.tv_details_ordertime)
    TextView tvdetails_ordertime;
    @BindView(R.id.tv_details_order)
    TextView tvdetails_order;
    @BindView(R.id.tv_details_paym)
    TextView tvdetails_paym;
    @BindView(R.id.tv_details_clientname)
    TextView tvdetails_clientname;
    @BindView(R.id.tv_details_title_cashier)
    TextView tvdetails_title_cashier;
    @BindView(R.id.tv_details_title_sktno)
    TextView tvdetails_title_sktno;
    @BindView(R.id.tv_details_title_version)
    TextView tvdetails_title_version;
    @BindView(R.id.tv_details_yhje)
    TextView tvdetails_yhje;
     @BindView(R.id.tv_details_totlemoney)
    TextView tvdetails_totlemoney;
    @BindView(R.id.tv_main_title_orderno)
    TextView tv_main_title_orderno;
     @BindView(R.id.tv_detail_title_currentTime)
    TextView tvdetail_title_currentTime;

    @BindView(R.id.rv_orderdetails_goodList)
    ListView rvorderdetails_goodList;
    @BindView(R.id.rv_orderquery_g)
    ListView lv_skfs;
    @BindView(R.id.details_th)
    Button detailsth;
    @BindView(R.id.details_linlayout)
    LinearLayout detailslinlayout;
    private final DetailsActivity.MyHandler handler = new DetailsActivity.MyHandler(this);

    @Override
    protected void initData() {
        jlbh = getIntent().getStringExtra("jlbh");
        sktno = getIntent().getStringExtra("sktno");
        orderNo = getIntent().getStringExtra("orderNo");
        begintime = getIntent().getStringExtra("begintime");
        endtime = getIntent().getStringExtra("endtime");
        detailsedittextorder.setText(begintime);
        detailsedittext_endtime.setText(endtime);
        tv_main_title_orderno.setText(orderNo);
        mTradeDetailsPresenter = new TradeDetailsPresenterImpl(this);
        dialog = new ProgressDialog(DetailsActivity.this);
        dialog.setCancelable(false);

        dialog.setMessage("正在查询明细，请稍等 ....");
        orderReq = new QueryOrderReq();
        orderReq.setOrderNo(orderNo);//
        orderReq.setSktno(sktno);
        mTradeDetailsPresenter.QueryTradeDetails(orderReq);//"单号查询",et_queryjlbh.getText().toString().trim()
        btndetailsexitsystem.setOnClickListener(this);
         detailsth.setOnClickListener(this);//退货

        tvdetails_title_cashier.setText(ErpCommonData.loadConfig.getCashierName() + "");
        tvdetails_title_sktno .setText(ErpCommonData.sktno + "");
        tvdetails_title_version.setText(CommonUtils.getCurrentVersionName(DetailsActivity.this));


        TimeThread timeThread = new TimeThread(handler);
        timeThread.setDaemon(true);//守护线程
        timeThread.start();

    }

    public static class MyHandler extends Handler {
        private final WeakReference<DetailsActivity> mActivity;

        public MyHandler(DetailsActivity activity) {
            this.mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            DetailsActivity detailsActivity = mActivity.get();
            if (detailsActivity == null) {
                return;
            }

            switch (msg.what) {
                case Constant.MAIN_UPDATE_CURRENT_TIME_HANDLEID: {
                    String time = msg.getData().getString("time");
                    detailsActivity.tvdetail_title_currentTime.setText(time);
                    break;
                }
                default:
                    break;
            }
        }
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_details;
    }



    @Override
    public void showProgress() {
        dialog.show();
    }

    @Override
    public void hideProgress() {
        dialog.dismiss();
    }

    @Override
    public void onTradeDetailsSuccess(List<Order> tradeDetailslist, double orderCount, RefundOrder data) {
        if (tradeDetailslist == null || tradeDetailslist.size() == 0) {
            ToastUtils.showMsg( "无小票信息");
            return;
        }
        tradeDetail=tradeDetailslist.get(0);//查询小票号就一条交易明细
        tvdetails_ordertime.setText(tradeDetailslist.get(0).getOrderTime());
        tvdetails_order.setText(tradeDetailslist.get(0).getOrderNo());
        tvdetails_paym.setText(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(tradeDetailslist.get(0).getTotalAmount())));
        tvdetails_clientname.setText("");//顾客姓名
        tvdetails_yhje.setText(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(tradeDetailslist.get(0).getTotalDiscount())));
        tvdetails_totlemoney.setText(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(tradeDetailslist.get(0).getTotalAmount())));


        //商品列表
        ArrayList<HashMap<String, Object>> goodslist = new ArrayList<HashMap<String, Object>>();
        for (Goods goods: tradeDetail.getSubTickets().get(0).getGoodsList()) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("name", goods.getName());
            map.put("price", MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getPrice())));
            map.put("count", goods.getSaleCount());
            map.put("preferential", MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getPreferentialMoney())));//优惠是指？
            map.put("amtmoneey", MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getSaleMoney())));//优惠是指？
            goodslist.add(map);
        }

        SimpleAdapter goodsAdapter = new SimpleAdapter(this, goodslist,
                R.layout.lvitem_goods_tradedetails,
                new String[] { "name", "price", "count","preferential","amtmoneey"}, new int[] {
                R.id.tv_goodsname_tradedetails, R.id.tv_goodsprice_tradedetails, R.id.tv_goodscount_tradedetails, R.id.tv_goodspreferential_tradedetails,R.id.tv_goodsmoney_tradedetails});
        rvorderdetails_goodList.setAdapter(goodsAdapter);

        //收款方式列表
        ArrayList<HashMap<String, Object>> payMents = new ArrayList<HashMap<String, Object>>();
         int i=1;
        for (Payment payment: tradeDetail.getPayList()) {

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("num", i);
            map.put("name", payment.getPayName());
            map.put("skje", MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(payment.getPayAmount())));
            map.put("paylsh", "0");
            payMents.add(map);
            i++;
        }
        // tvPrice.setText();

        SimpleAdapter paymentAdapter = new SimpleAdapter(this, payMents,
                R.layout.lvitem_payment_tradedetails,
                new String[] { "num", "name", "skje","paylsh" }, new int[] {
                R.id.tv_goodetailsnum, R.id.tv_paymentname, R.id.tv_salemoney_tradedetails, R.id.tv_paylsh_tradedetails });
        lv_skfs.setAdapter(paymentAdapter);

        DividerItemDecoration mDividerItemDecoration = new DividerItemDecoration(DetailsActivity.this, DividerItemDecoration.VERTICAL);
        mDividerItemDecoration.setDrawable(new ColorDrawable(ContextCompat.getColor(DetailsActivity.this,R.color.main_good_info_bar)));

    }

    @Override
    public void showLoadFailMsg(String errorMsg) {
        ToastUtils.showMsg("查询小票失败"+errorMsg);

    }

    @Override
    public void onClick(View v) {
         switch (v.getId()){
             case R.id.btn_details_exit_system:
                 finish();
                 break;
             case R.id.details_th: //退货
                 TicketInfo  ticketInfo= new TicketInfo();
                 ticketInfo.setSubTickets(tradeDetail.getSubTickets());
                 ticketInfo.setOfferCouponList(tradeDetail.getOfferCouponList());
                 ticketInfo.setPayList(tradeDetail.getPayList());
                 ticketInfo.setLottoList(tradeDetail.getLottoList());
                 ticketInfo.setCasherInfo(tradeDetail.getCasherInfo());
                 ticketInfo.setMemberInfo(tradeDetail.getMemberInfo());
                 ticketInfo.setJlbh(tradeDetail.getJlbh());
                 ticketInfo.setOrderNo(tradeDetail.getOrderNo());
                 ticketInfo.setOrderTime(tradeDetail.getOrderTime());
                 if (tradeDetail.getPayList().size()>0){
                     for (Payment payment:tradeDetail.getPayList()){
                         if (payment.getPayInfoList().size()>0){
                             for (PayInfo payInfo:payment.getPayInfoList()){
                                 if (payment.getPayType()==Payment.SKFS_WX){
                                     O2OPayDetail o2o=new O2OPayDetail();
                                     o2o.setTotalFee(MoneyUtils.getMoneyInt(payInfo.getPay_amount()));
                                     o2o.setOutTradeNo(payInfo.getOutTradeNo());
                                     o2o.setTransactionId(payInfo.getTransactionId());
                                     o2o.setSktno(tradeDetail.getSktno());
                                     o2o.setJysj(payInfo.getPay_time());
                                     o2o.setPayCode(payment.getPayCode());
                                     ticketInfo.getO2oWxList().add(o2o);
                                 }else if (payment.getPayType()==Payment.SKFS_ZFB){
                                     O2OPayDetail o2o=new O2OPayDetail();
                                     o2o.setTotalFee(MoneyUtils.getMoneyInt(payInfo.getPay_amount()));
                                     o2o.setOutTradeNo(payInfo.getOutTradeNo());
                                     o2o.setTransactionId(payInfo.getTransactionId());
                                     o2o.setSktno(tradeDetail.getSktno());
                                     o2o.setJysj(payInfo.getPay_time());
                                     o2o.setPayCode(payment.getPayCode());
                                     ticketInfo.getO2oZfbList().add(o2o);
                                 }else if(payment.getPayType()==Payment.SKFS_YHK ){
                                     YhkCardItem item= new YhkCardItem();
                                     item.setAmount(payInfo.getPay_amount());
                                     item.setLsh(payInfo.getPay_lsh());
                                     item.setCkh(payInfo.getPay_ckh());
                                     item.setPzh(payInfo.getPay_pzh());
                                     item.setCardNo(payInfo.getPay_cardNo());
                                     item.setType(payment.getPayType()+"");
                                     ticketInfo.getBankCardList().add(item);
                                 }else if(payment.getPayType()==Payment.SKFS_JH ){
                                     if (payment.getPayCode() ==2){
                                         O2OPayDetail o2o=new O2OPayDetail();
                                         o2o.setTotalFee(MoneyUtils.getMoneyInt(payInfo.getPay_amount()));
                                         o2o.setOutTradeNo(payInfo.getOutTradeNo());
                                         o2o.setTransactionId(payInfo.getTransactionId());
                                         o2o.setSktno(tradeDetail.getSktno());
                                         o2o.setJysj(payInfo.getPay_time());
                                         o2o.setPayCode(payment.getPayCode());
                                         ticketInfo.getO2oZfbList().add(o2o);
                                     }else if (payment.getPayCode() ==3){
                                         O2OPayDetail o2o=new O2OPayDetail();
                                         o2o.setTotalFee(MoneyUtils.getMoneyInt(payInfo.getPay_amount()));
                                         o2o.setOutTradeNo(payInfo.getOutTradeNo());
                                         o2o.setTransactionId(payInfo.getTransactionId());
                                         o2o.setSktno(tradeDetail.getSktno());
                                         o2o.setJysj(payInfo.getPay_time());
                                         o2o.setPayCode(payment.getPayCode());
                                         ticketInfo.getO2oWxList().add(o2o);
                                     }
                                 }
                             }
                         }
                     }
                 }




                 Intent intent=new Intent(DetailsActivity.this,RefundActivity.class);
                 intent.putExtra("TicketInfo",ticketInfo);
                 intent.putExtra("old_sktno",tradeDetail.getSktno());
                 intent.putExtra("old_orderNo",tradeDetail.getOrderNo());
                // intent.putExtra("managerNo",managerNo);
                 intent.putExtra("isAllOrder",false);//是否整单退货
                 startActivity(intent);

                 break;
         }
    }
}
